package com.hunt.app.task;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.*;

/**
 * @author ww
 * @className
 * @description
 * @date 2020/11/4
 */
//@Component
public class FiveMinRealtimeStockDataTask {

    private static final Logger log = LoggerFactory.getLogger(FiveMinRealtimeStockDataTask.class);

    //集群抢锁
    private static final String FIVE_MINUTES_REAL_TIME_DATA_KEY = "FIVE_MINUTES_REAL_TIME_DATA_KEY";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JedisPool jedisPool;

    //每天9点执行
    @Scheduled(cron = "30 1/5 9,10,11,13,14 * * ? ")
    public void taskStarter() {

        //集群部署情况做分布式锁抢占式 返回true抢到了锁  返回false没抢到直接return
        Boolean b = redisTemplate.opsForValue().setIfAbsent(FIVE_MINUTES_REAL_TIME_DATA_KEY, "The_timer_is_Executing");
        if (!b){
            return;
        }
        log.info("每5分钟更新涨跌幅数据定时器启动...");
        Jedis redis = null;
        try {
            redis = jedisPool.getResource();
            Map<String,String> map = redis.hgetAll("Real_time_Stock_Data");
            if (map == null || map.isEmpty()){
                return;
            }
            Map<String,String> fiveMinDataMap = new HashMap<>();
            Set<Map.Entry<String,String>> entries = map.entrySet();
            Iterator<Map.Entry<String,String>> it = entries.iterator();
            while (it.hasNext()){
                try {
                    Map.Entry<String,String> entry = it.next();
                    String key = entry.getKey();
                    String volValue = JSONObject.parseObject(entry.getValue()).getString("hlPercent");
                    fiveMinDataMap.put(key,volValue);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            redis.hmset("Five_Minute_Stock_HlPercent", fiveMinDataMap);
            Thread.sleep(5000);
            log.info("每5分钟更新涨跌幅实时数据定时器执行成功,并已经释放执行锁");
        }catch (Exception e){
            log.info("每5分钟更新涨跌幅实时数据定时器执行失败,并已经释放执行锁");
            e.printStackTrace();
        }finally {
            if (redis != null){
                redis.close();
            }
            redisTemplate.delete(FIVE_MINUTES_REAL_TIME_DATA_KEY);
        }
    }
}
